<template>
  <div>
    <!-- 顶部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="警告提示的文案" type="warning"></el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            expandTrigger="hover"
            v-model="selectedCateKeys"
            :options="catelist"
            :props="cataprops"
            @change="catehandleChange"
          ></el-cascader>
          <!-- 标签页 -->
          <el-tabs v-model="activeName" @tab-click="handletabClick">
            <el-tab-pane label="动态参数" name="many">
              <el-button
                size="mini"
                type="primary"
                :disabled="isButtonDisabled"
                @click="adddialogVisible = true"
              >添加参数</el-button>
              <!-- 动态参数 -->
              <el-table border :data="mangTable" stripe>
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <!-- 展开参数 -->
                  <template v-slot:default="scope">
                    <!-- 循环生成的el-tag -->
                    <el-tag
                      v-for="(item,i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>
                    <!-- 输入框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <!-- 添加按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                  <template v-slot:default="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="showeditdialog(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="removeParams(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
              <el-button
                size="mini"
                type="primary"
                :disabled="isButtonDisabled"
                @click="adddialogVisible = true"
              >添加属性</el-button>
              <!-- 静态属性 -->
              <el-table border :data="onlyTable" stripe>
                <!-- 展开行 -->
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <!-- 展开参数 -->
                  <template v-slot:default="scope">
                    <!-- 循环生成的el-tag -->
                    <el-tag
                      v-for="(item,i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>
                    <!-- 输入框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <!-- 添加按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                  <template v-slot:default="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="showeditdialog(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="removeParams(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 动态参数弹出框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="adddialogClose"
    >
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数弹出框 -->
    <!-- 动态参数弹出框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editdialogClose"
    >
      <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      catelist: [],
      // 用户在级联下拉菜单中选中的分类id
      selectedCateKeys: [],
      cataprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      // 动态参数数据
      mangTable: [],
      // 静态属性数据
      onlyTable: [],
      adddialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormrules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      editdialogVisible: false,
      editForm: {},
      editFormrules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getparamslist()
  },
  methods: {
    async getparamslist() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      // this.$message.success('获取成功')
      this.catelist = res.data
      console.log(res.data)
    },
    catehandleChange() {
      this.paramsdata()
    },
    handletabClick() {
      console.log(this.activeName)
      this.paramsdata()
    },
    // 切换tab面板 获取不同列表参数
    async paramsdata() {
      console.log(this.selectedCateKeys)
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.mangTable = []
        this.onlyTable = []
        return
      }
      // 选择三级分类
      // console.log(this.selectedCateKeys)
      // 根据所选的id，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$meesage.error('获取失败')
      }
      console.log(res.data)
      // 将获取到的数据中的attr_vals字符串转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加一个bool值控制文本框的显示或者隐藏
        item.inputVisible = false
        // 添加一个inputValue保存文本框值
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.mangTable = res.data
      } else {
        this.onlyTable = res.data
      }
    },
    AddTable() {
      this.adddialogVisible = true
    },
    adddialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    addParams() {
      // 当用户点击对话框中的确定时，校验表单
      this.$refs.addFormRef.validate(async valid => {
        // 校验不通过，return
        if (!valid) return
        // 校验通过，发送请求完成添加参数或者属性
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: 'a,b,c'
          }
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加' + this.titleText + '数据失败')
        }
        this.$message.success('添加' + this.titleText + '数据成功')
        this.adddialogVisible = false
        this.getparamslist()
      })
    },
    // 修改参数
    async showeditdialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数数据失败')
      }
      this.editForm = res.data
      this.editdialogVisible = true
    },
    editdialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    editParams() {
      // 验证表单
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发送请求完成修改
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取参数数据失败')
        }
        this.$message.success('修改' + this.titleText + '数据成功')
        this.editdialogVisible = false
        this.catehandleChange()
      })
    },
    // 文本框失去焦点
    // 最后对应文本框的事件和按钮的事件添加处理函数
    async handleInputConfirm(row) {
      // 当用户在文本框中按下enter键或者焦点离开时都会触发执行
      // 判断用户在文本框中输入的内容是否合法
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return console.log('不合法')
      }

      // row.inputVisible = false
      // 如果用户输入了真实合法的数据，需要保存起来
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    showInput(row) {
      // 用户点击添加按钮时触发
      row.inputVisible = true
      // $nextTick:在页面上元素被重新渲染之后，调用回调函数的代码
      this.$nextTick(_ => {
        // 让文本框自动获得焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveAttrVals(row) {
      // 封装函数，完成保存可选项的操作
      // 发起请求，保存参数细项
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }

      this.$message.success('修改参数项成功')
    },
    // 删除对应的参数和选项
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    async removeParams(id) {
      const confirmResult = await this.$confirm(
        '请问是否要删除该' + this.titleText,
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      console.log(res.data)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除' + this.titleText + '成功')
      this.catehandleChange()
    }
  },
  computed: {
    // 如果按钮需要被禁用，则返回true 否返回false
    isButtonDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.input-new-tag {
  width: 120px;
}
</style>
